//
//  StatusPictureView.swift
//  glzbowei
//
//  Created by 高伦展 on 2018/1/7.
//  Copyright © 2018年 glz. All rights reserved.
//

import UIKit
import SDWebImage

private let StatusPictureViewItemMargin:CGFloat = 8
private let StatusPictureCellId = "StatusPictureCellId"

class StatusPictureView: UICollectionView {
    
    //微博视图模型
    var viewModel:StatusViewModel?{
        didSet{
            sizeToFit()
            //刷新数据 - 如果不刷新，后续的collectionView 一旦被复用，不再调用数据源方法
            reloadData()
        }
    }
    
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        return calcViewSize()//CGSize(width: 200, height: Int(90 * (arc4random() % 4)))
    }
    
    init(){
        let layout = UICollectionViewFlowLayout()
        
        //设置间距 - 默认 itemSize 50 * 50
        layout.minimumLineSpacing = StatusPictureViewItemMargin
        layout.minimumInteritemSpacing = StatusPictureViewItemMargin
        
        super.init(frame: CGRect.zero, collectionViewLayout: layout)
        
        self.backgroundColor = UIColor(white: 0.9, alpha: 0.5)
        
        //设置数据源 - 自己当自己的数据源
        dataSource = self
        //设置代理
        delegate = self
        
        register(StatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureCellId)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: - UICollectionViewDataSource
extension StatusPictureView:UICollectionViewDataSource,UICollectionViewDelegate{
    
    //选中照片
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //print("点击照片 \(indexPath) \(String(describing: viewModel?.thumbnailUrls))")
        photoBrowserPresentFromRect(indexPath: indexPath)
        
        //明确问题：传递什么数据？当前 URL 的数组/当前用户选中的索引
        //如何传递：通知
        //通知：名字（通知中心监听）/object；发送通知的同时传递对象（单值）/userInfo：传递多值的时候，使用的数据字典->Key
        
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBStatusSelectedPhotoNotification),
                                        object: self,
                                        userInfo:[WBStatusSelectedPhotoIndexPathKey:indexPath,                                     WBStatusSelectedPhotoURLsKey:viewModel!.thumbnailUrls])
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.thumbnailUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: StatusPictureCellId, for: indexPath) as! StatusPictureViewCell
        
        cell.imageURL = viewModel!.thumbnailUrls![indexPath.item]
        
        return cell
    }
    
}


// MARK:-照片查看器的展现协议
extension StatusPictureView : PhotoBrowserPresentDelegate{
    func imageViewForPresent(indexPath: IndexPath) -> UIImageView {
        let iv = UIImageView()
        
        iv.contentMode = .scaleAspectFill
        iv.clipsToBounds = true
        
        if let url = viewModel?.thumbnailUrls?[indexPath.item]{
            iv.sd_setImage(with: url, completed: { (image, _, _, _) in
                
            })
        }
        
        return iv
    }
    
    func photoBrowserPresentFromRect(indexPath: IndexPath) -> CGRect {
        //根据indexPath获取当前用户选择的cell
        let cell = self.cellForItem(at: indexPath)!
        //通过cell知道cell对应在屏幕上的准确位置
        
        let rect = self.convert(cell.frame, to: UIApplication.shared.keyWindow!)
        
        return rect
    }
    
    func photoBrowserPresentToRect(indexPath: IndexPath) -> CGRect {
       
        guard let key = viewModel?.thumbnailUrls?[indexPath.item].absoluteString else{
            return CGRect.zero
        }
        
        guard let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: key) else{
            return CGRect.zero
        }
        
        let w = UIScreen.main.bounds.width
        let h = image.size.height * w / image.size.width
        
        let screenHeight = UIScreen.main.bounds.height
        var y:CGFloat = 0
        if h < screenHeight{
            y = (screenHeight - h ) * 0.5
        }
        
        return CGRect(x: 0, y: y, width: w, height: h)
    }
    
    
}

//MARK: - 计算视图大小
extension StatusPictureView{
    
    private func calcViewSize() -> CGSize {
        
        //每行照片数
        let rowCount :CGFloat = 3
        
        let maxWidth = UIScreen.main.bounds.width - 2 * StatusCellMargin
        let iw = String(format:"%.3f", (maxWidth - 2 * StatusPictureViewItemMargin) / rowCount);
        let itemWidth = CGFloat(Double(iw)! - 0.001);
        
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        //获取图片数量
        let count = viewModel?.thumbnailUrls?.count ?? 0
        
        if count == 0 {
            return CGSize.zero
        }
        
        if count == 1 {
            var size = CGSize(width: 150, height: 120)
            
            //利用SDWebImage 检查本地的缓存图片 - key 就是 url的完整字符串
            //SDWebImage 是如何设置缓存图片的文件名 完整url字符串 -> MD5
            if let key = viewModel?.thumbnailUrls?.first?.absoluteString{
                if let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: key){
                    size = (image.size)
                }
            }
            
            size.width = size.width < 40 ? 40 : size.width
            
            if size.width > 300 {
                let w:CGFloat = 300
                let h = size.height * w / size.width
                size = CGSize(width: w, height: h)
            }
            
            layout.itemSize = size
            return size
        }
        
        if count == 4 {
            let w = 2 * itemWidth + StatusPictureViewItemMargin
        
            return CGSize(width: w, height: w)
        }
        
        let row = CGFloat((count - 1) / Int(rowCount) + 1)
        let h = row * itemWidth + (row - 1) * StatusPictureViewItemMargin
        let w = rowCount * itemWidth + (rowCount - 1) * StatusPictureViewItemMargin
        
        return CGSize(width: w, height: h)
    }
}

// MARK: - 配图 Cell
private class StatusPictureViewCell : UICollectionViewCell{
    
    var imageURL : URL?{
        didSet{
            iconView.sd_setImage(with: imageURL,
                                 placeholderImage: nil,
                                 options: [SDWebImageOptions.retryFailed,SDWebImageOptions.refreshCached])
            
            let ext = ((imageURL?.absoluteString ?? "") as String).hasSuffix(".gif")
            
            gifIconView.isHidden = ext
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        contentView.addSubview(iconView)
        iconView.addSubview(gifIconView)
        //iconView.frame = bounds
        
        iconView.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView.snp.edges)
        }
        
        gifIconView.snp.makeConstraints { (make) in
            make.right.equalTo(iconView.snp.right)
            make.bottom.equalTo(iconView.snp.bottom)
        }
    }
    
    private lazy var iconView:UIImageView = {
        let iv = UIImageView()
        
        iv.contentMode = .scaleAspectFill
        iv.clipsToBounds = true
        return iv
    }()
    
    private lazy var gifIconView : UIImageView = UIImageView(imgName: "timeline_image_gif")
    
}

